package com.sinogrand.elevator.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.draw.shadow
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.sinogrand.elevator.ui.components.ProjectItem
import com.sinogrand.elevator.ui.components.ProjectOverviewTab
import com.sinogrand.elevator.ui.components.ElevatorListTab
import com.sinogrand.elevator.ui.components.MemberListTab
import com.sinogrand.elevator.data.models.ElevatorItem
import com.sinogrand.elevator.data.models.ProjectDetailData
import com.sinogrand.elevator.network.NetworkClient
import androidx.compose.ui.platform.LocalContext
import com.google.gson.JsonObject

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProjectDetailScreen(
    project: ProjectItem,
    onBackClick: () -> Unit,
    onElevatorClick: (ElevatorItem) -> Unit = {}
) {
    var selectedTab by rememberSaveable { mutableStateOf(0) }
    
    // 项目详情状态
    var projectDetailData by remember { mutableStateOf<ProjectDetailData?>(null) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    
    val context = LocalContext.current
    val apiService = remember { NetworkClient.getApiService(context) }
    
    val tabs = listOf("概况", "电梯", "组员")
    
    // 获取项目详情的函数
    suspend fun loadProjectDetail() {
        try {
            isLoading = true
            errorMessage = null
            
            // 构建请求参数
            val request = JsonObject().apply {
                addProperty("id", project.id.toInt())
            }
            
            // 调用API获取数据
            val apiResponse = apiService.getProjectInfo(request)
            
            if (apiResponse.code == 0 && apiResponse.data != null) {
                projectDetailData = apiResponse.data
            } else {
                // API失败时显示错误信息
                projectDetailData = null
                errorMessage = "API请求失败: ${apiResponse.msg}"
            }
        } catch (e: Exception) {
            // 异常时显示错误信息
            projectDetailData = null
            errorMessage = "网络请求异常: ${e.message}"
        } finally {
            isLoading = false
        }
    }
    
    // 初始化数据
    LaunchedEffect(project.id) {
        loadProjectDetail()
    }
    
    // 计算显示的标题
    val displayTitle = when {
        isLoading -> "" // 加载中不显示标题
        projectDetailData != null -> projectDetailData!!.info.name // 获取到详情后显示项目名称
        else -> "" // 加载失败也不显示标题
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = displayTitle,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF1F2937)
                    )
                },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回",
                            tint = Color(0xFF374151)
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.White,
                    titleContentColor = Color(0xFF1F2937)
                ),
                modifier = Modifier.shadow(2.dp)
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    Brush.verticalGradient(
                        colors = listOf(
                            Color(0xFFF8FAFC),
                            Color(0xFFF1F5F9)
                        )
                    )
                )
                .padding(paddingValues)
        ) {
        
        // Tab选择器
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 8.dp),
            colors = CardDefaults.cardColors(
                containerColor = Color.White
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
            shape = RoundedCornerShape(12.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(4.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                tabs.forEachIndexed { index, tabTitle ->
                    TabButton(
                        text = tabTitle,
                        isSelected = selectedTab == index,
                        onClick = { selectedTab = index },
                        modifier = Modifier.weight(1f)
                    )
                }
            }
        }
        
        // Tab内容区域
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
        ) {
            when (selectedTab) {
                0 -> ProjectOverviewTab(project = project)
                1 -> ElevatorListTab(project = project, onElevatorClick = onElevatorClick)
                2 -> MemberListTab(project = project)
            }
        }
        }
    }
}

@Composable
fun TabButton(
    text: String,
    isSelected: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    if (isSelected) {
        Card(
            modifier = modifier
                .padding(2.dp)
                .clip(RoundedCornerShape(8.dp)),
            colors = CardDefaults.cardColors(
                containerColor = Color(0xFF3B82F6)
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
        ) {
            TextButton(
                onClick = onClick,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    text = text,
                    color = Color.White,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Bold
                )
            }
        }
    } else {
        TextButton(
            onClick = onClick,
            modifier = modifier.fillMaxWidth()
        ) {
            Text(
                text = text,
                color = Color(0xFF6B7280),
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium
            )
        }
    }
}
